package com.glory.dgcpcpda.activity.mfg;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.adapter.AddCarrierDataAdapter;
import com.glory.dgcpcpda.adapter.MaterielListAdapter;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.base.Constant;
import com.glory.dgcpcpda.base.MyApp;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.entity.AdrefListEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.LotList;
import com.glory.dgcpcpda.entity.MaterielListEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_CommonCallback;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralFragmentDialog;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_DialogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * FileName: WBWorkBeginActivity
 * Author: XJH
 * Date: 2020/5/21 10:22
 * Description:开始作业WB工序
 * History:
 */
public class WBWorkBeginActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.tvBDNum)
    TextView tvBDNum;
    @BindView(R.id.tvRecipeID)
    TextView tvRecipeID;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.etMaterielModel)
    FreeUI_ClearEditText etMaterielModel;
    @BindView(R.id.rvMaterielModelList)
    RecyclerView rvMaterielModelList;
    @BindView(R.id.etMaterielBox)
    FreeUI_ClearEditText etMaterielBox;
    @BindView(R.id.rvMaterielBoxList)
    RecyclerView rvMaterielBoxList;
    @BindView(R.id.rvMaterielList)
    RecyclerView rvMaterielList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.etUserName)
    FreeUI_ClearEditText etUserName;
    @BindView(R.id.llBoxLayout)
    LinearLayout llBoxLayout;
    @BindView(R.id.llCarrierLayout)
    LinearLayout llCarrierLayout;
    @BindView(R.id.etBingLotID)
    FreeUI_ClearEditText etBingLotID;
    @BindView(R.id.tvBingLotID)
    TextView tvBingLotID;
    @BindView(R.id.rvLotList)
    RecyclerView rvLotList;
    @BindView(R.id.etLocatorId)
    TextView etLocatorId;
    private AddCarrierDataAdapter materielModelAdapter;
    private AddCarrierDataAdapter materielBoxAdapter;
    private MaterielListAdapter materielListAdapter;
    private List<String> mDurablelist = new ArrayList<>();
    private String needEqp;
    String type;
    private AddCarrierDataAdapter carrierAdapter;
    private  ArrayList<String> StepNameList = new ArrayList<>();
    private  ArrayList<String> StepNameList1 = new ArrayList<>();//不允许进站工序列表
    private String StepName = "";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_track_in_wb;
    }

    @Override
    protected void initView() {
        tvTitle.setText("开始作业");
        setMainLayout(llMain);
        needEqp="";
        type="";
        StepName = "";
        llCarrierLayout.setVisibility(View.GONE);
        initRecyclerView(rvMaterielModelList, this);
        initRecyclerView(rvMaterielBoxList, this);
        initRecyclerView(rvMaterielList,this);
        initRecyclerView(rvLotList,this);
        materielModelAdapter = getCarrierAdapter();
        rvMaterielModelList.setAdapter(materielModelAdapter);
        materielBoxAdapter = getCarrierAdapter();
        rvMaterielBoxList.setAdapter(materielBoxAdapter);
        carrierAdapter = getCarrierAdapter();
        rvLotList.setAdapter(carrierAdapter);

        materielListAdapter = new MaterielListAdapter(null);
        materielListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        materielListAdapter.isFirstOnly(true);
        rvMaterielList.setAdapter(materielListAdapter);
        showCarrierLayout1();//获取不允许在此功能进行操作工序

        etMaterielModel.setVisibility(Constant.CARRIER_DURABLELIST ? View.VISIBLE : View.GONE);
        etMaterielBox.setVisibility(Constant.CARRIER_DURABLELIST ? View.VISIBLE : View.GONE);
        initEdit2(etMaterielModel, s -> {

            if (mDurablelist == null){
                showToast("请先扫描批次号!", false);
                return;
            }


            if (materielModelAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }

            if (mDurablelist.contains(s)){
                materielModelAdapter.getData().add(s);
                materielModelAdapter.notifyDataSetChanged();
            }else {
                showConfirmDialog(s+"与当前载具不匹配!");
//                showToast("当前载具不匹配!", false);
            }

        });

        initEdit2(etBingLotID,s ->{
            new Handler().postDelayed(() -> etBingLotID.setText(""),500);
            if (mDurablelist == null){
                showToast("请先扫描批次号!", false);
                return;
            }


            if (carrierAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }

            if(!StepNameList.contains(StepName)){
                if (mDurablelist.contains(s)){
                    carrierAdapter.addData(s);
                }else {
                    showConfirmDialog(s+"与当前载具不匹配!");
                }
            }
            else{
                carrierAdapter.addData(s);
            }



//            LotUtils.checkCarrier(WBWorkBeginActivity.this,getText(etLot),s, getSupportFragmentManager(), new LotUtils.netCallback<Object>() {
//
//                @Override
//                public void onSuccess(Object response) {
//                    if (mDurablelist.contains(s)){
//                        carrierAdapter.addData(s);
//                    }else {
//                        showConfirmDialog(s+"与当前载具不匹配!");
////                        showToast("当前载具不匹配!", false);
//                    }
//                }
//
//                @Override
//                public void onFail(Throwable t) {
//                    loadError(t, "CHECKCARRIER");
//                }
//            });

        });

        initEdit2(etMaterielBox, s -> {

            if (mDurablelist == null){
                showToast("请先扫描批次号!", false);
                return;
            }


            if (materielBoxAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }

            if (mDurablelist.contains(s)){
                materielBoxAdapter.getData().add(s);
                materielBoxAdapter.notifyDataSetChanged();
            }else {
                showToast("当前载具不匹配!", false);
            }
        });

        initEdit(etLot, s -> {
            //获取lot信息
            LotUtils.searchLotInfo(WBWorkBeginActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    tvBDNum.setText(response.getWIRINGNO());
                    mDurablelist.clear();
                    mDurablelist = response.getDURABLELIST();
                    if(response.getLOT().getSTEPDESC().contains("装片")){
                        showConfirmDialog("装片工序请用[DA开始作业]进站");
                        return;
                    }
                    StepName = response.getLOT().getSTEPNAME();
                    if (StepNameList1.contains(StepName)){
                        FreeUI_GeneralFragmentDialog tipDialog = FreeApi_DialogUtils.getConfirmDialog(MyApp.app, "确定", "当前工序:"+response.getLOT().getSTEPDESC()+"("+StepName+")不允许在此功能进行操作", () -> {
                            finish();
                        });
                        tipDialog.show(getSupportFragmentManager(),"DIALOG");
                        return;
                    }

                    showCarrierLayout(response);
                    tvTitle.setText("开始作业" + "(" + response.getLOT().getSTEPDESC() + ")");
                    String state = response.getLOT().getSTATE();
                    if(state.equals("正在作业")){
                        state = state + " - " + response.getLOT().getEQUIPMENTID();
                    }
                    tvLotState.setText(state);

                    if (!Constant.CARRIER_DURABLELIST){
                        materielModelAdapter.setNewData(mDurablelist);
                    }
                    if(StringUtils.isNotEmpty(response.getEQPNEEDED())){
                        if("1024107".equals(response.getEQPNEEDED())){
                            needEqp="NO";
                            etEqpWorkID.setHint("当前工序不需要设备");
                            etEqpWorkID.setEnabled(false);

                            etUserName.setFocusable(true);
                            etUserName.requestFocus();
                            etUserName.setFocusableInTouchMode(true);
                            etUserName.requestFocusFromTouch();

                        }else{
                            needEqp="YES";
                            etEqpWorkID.setHint("请扫描设备编号");
                            etEqpWorkID.setEnabled(true);

                            etEqpWorkID.setFocusable(true);
                            etEqpWorkID.requestFocus();
                            etEqpWorkID.setFocusableInTouchMode(true);
                            etEqpWorkID.requestFocusFromTouch();

                        }

                    }
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });

            initEdit(etEqpWorkID, s -> getKittingInfo(s));

    }

    /**
     * 是否显示载具
     * @param data
     */
    private void showCarrierLayout(LotInfoEntity data) {
        FreeUI_EntityCallBack<BaseResponseBean<AdrefListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AdrefListEntity>>
                (new TypeToken<BaseResponseBean<AdrefListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<AdrefListEntity.Adref> adreflist = response.body().getResponse().getBody().getADREFLIST();
                    StepNameList.clear();
                    llCarrierLayout.setVisibility(View.GONE);
                    for (AdrefListEntity.Adref entity : adreflist) {
                        if(entity.getKEY().equals("REVERSE")){
                            StepNameList.add(entity.getTEXT());
                        }
                        if (entity.getTEXT().equals(data.getLOT().getSTEPNAME()) && entity.getDESCRIPTION().equals(data.getPACKAGETYPE())) {
                            llCarrierLayout.setVisibility(View.VISIBLE);
                            tvBingLotID.setText("料框/料盒：");
                            etBingLotID.setHint("请扫描料框/料盒");
                        }
                        else if (entity.getTEXT().equals(data.getLOT().getSTEPNAME()) && entity.getDESCRIPTION().equals(data.getLOT().getUDF().getPACKAGECODE())) {
                            llCarrierLayout.setVisibility(View.VISIBLE);
                            tvBingLotID.setText("料框/料盒：");
                            etBingLotID.setHint("请扫描料框/料盒");
                        }
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME","CPC_CARRIERS_CHECK_STEP");
        NetUtils.requestPostNet("CPC.ADREFLISTQUERY","ADREFLISTQUERY",this,map,callBack);
    }

    //获取不允许进站工序
    private void showCarrierLayout1() {
        FreeUI_EntityCallBack<BaseResponseBean<AdrefListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AdrefListEntity>>
                (new TypeToken<BaseResponseBean<AdrefListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<AdrefListEntity.Adref> adreflist = response.body().getResponse().getBody().getADREFLIST();
                    StepNameList1.clear();
                    for (AdrefListEntity.Adref entity : adreflist) {
                        StepNameList1.add(entity.getKEY());
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME","DianDu__NoAllow_CheckInOut");
        NetUtils.requestPostNet("CPC.ADREFLISTQUERY","ADREFLISTQUERY",this,map,callBack);
    }

    private void getKittingInfo(String eqpID) {
        FreeUI_EntityCallBack<BaseResponseBean<MaterielListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<MaterielListEntity>>
                (new TypeToken<BaseResponseBean<MaterielListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(WBWorkBeginActivity.this, true, getSupportFragmentManager())) {
                    materielListAdapter.setNewData(response.body().getResponse().getBody().getMLOTLIST());
                   List<MaterielListEntity.Materiel>  materielListEntityList=response.body().getResponse().getBody().getMLOTLIST();
                   for(MaterielListEntity.Materiel materielListEntity : materielListEntityList){
                       Map map= (Map) materielListEntity.getUDF();
                       if(map != null){
                           String rcmsg=(String) map.get("rcmsg");
                           if(rcmsg!=null){
                               String rcmLeftTime=(String) map.get("rcmLeftTime");
                               showToast("该树脂距离过期时间还剩"+rcmLeftTime+"分钟,请注意！",false);
                           }
                       }
                    }
                }

            }

            @Override
            public void onError(Response<BaseResponseBean<MaterielListEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "MLOTKITTING");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "LOAD");
        map.addProperty("EQUIPMENTID", eqpID);
        NetUtils.requestPostNet("CPC.MLOTKITTING", "MLOTKITTING", WBWorkBeginActivity.this, map, callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick(R.id.tvBaseSubmit)
    public void onViewClicked() {
        if (actionControl("Submit23"))
            return;

        if (tvLotState.getText().toString().equals("待投产")){
            showConfirmDialog("批次未投产，请联系计划部执行投产");
            return;
        }

        if (tvLotState.getText().toString().contains("正在作业")){
            showConfirmDialog("批次正在作业，请直接操作出站功能");
            return;
        }

        if (getText(etUserName).equals("")){
            showToast("请输入工号",false);
            return;
        }

        if (llCarrierLayout.getVisibility() == View.VISIBLE){
            if(!StepNameList.contains(StepName)){
                if (carrierAdapter.getData().size() != mDurablelist.size()){
                    showToast("载具验证未完成",false);
                    return;
                }
            }
        }

        if("YES".equals(needEqp)){
            type="DefaultTrackIn";
            if("".equals(getText(etEqpWorkID))){
                showToast("请输入设备号",false);
                return;
            }
        }else{
            type="NoEqpTrackIn";
        }

       LotUtils.lotTrackIn(getSupportFragmentManager(), this, getText(etUserName),getText(etEqpWorkID), getText(etLot),carrierAdapter.getData(),type);

    }

}
